package core.util;

import cache.Cache;
import cache.CacheManager;
import domain.entity.base.AgentInfo;
import domain.entity.base.UserInfo;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Created by bowen on 2017-08-14.
 */
public class ValidationUtil {

    private static final Logger logger = Logger.getLogger(ValidationUtil.class);

    public static boolean debug;
    public static String corpId;
    public static String agentId;
    public static String secret;
    public static String baidu_ak;


    static {
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("validation");
            debug = Boolean.valueOf(bundle.getString("wx.config.debug"));
            corpId = bundle.getString("wx.config.corpId");
            agentId = bundle.getString("wx.config.agentId");
            secret = bundle.getString("wx.config.secret");
            baidu_ak = bundle.getString("baidu.ak");
        } catch (MissingResourceException e) {
            logger.warn("未找到validation配置文件");
        }
    }


    private static String getAccessToken() throws Exception {
        String key = "access_token";
        Cache cache = CacheManager.getCacheInfo(key);
        if (cache == null) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CORP_ID&corpsecret=CORP_SECRET";
            url = url.replace("CORP_ID", corpId).replace("CORP_SECRET", secret);
            ClientRequest request = new ClientRequest(url);
            request.accept("application/json");
            ClientResponse<String> response = request.get(String.class);
            String responseContent = (String) response.getEntity();
            System.out.println(responseContent);
            JSONObject json = JSONObject.fromObject(responseContent);
            if ("0".equals(json.get("errcode").toString())) {
                cache = new Cache(key, json.get("access_token").toString(), json.getLong("expires_in"), Boolean.TRUE);
                CacheManager.putCache(key, cache);
            } else if ("40001".equals(json.get("errcode").toString())||"42001".equals(json.get("errcode").toString())) {
                CacheManager.clearOnly("access_token");
                getAccessToken();
            }
        }
        return cache.getValue().toString();
    }


    public static String getTicket() throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN";
        url = url.replace("ACCESS_TOKEN", getAccessToken());
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        System.out.println(responseContent);
        JSONObject json = JSONObject.fromObject(responseContent);
        if ("0".equals(json.get("errcode").toString())) {
            return json.get("ticket").toString();
        } else if ("40001".equals(json.get("errcode").toString())||"42001".equals(json.get("errcode").toString())) {
            CacheManager.clearOnly("access_token");
            getTicket();
        }
        return null;
    }

    public static AgentInfo getAgentInfo() throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token=ACCESS_TOKEN&agentid=AGENT_ID";
        url = url.replace("ACCESS_TOKEN", getAccessToken()).replace("AGENT_ID", agentId);
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        System.out.println(responseContent);
        JSONObject json = JSONObject.fromObject(responseContent);
        if ("0".equals(json.get("errcode").toString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            return objectMapper.readValue(responseContent, new TypeReference<AgentInfo>() {
            });
        } else if ("40001".equals(json.get("errcode").toString())||"42001".equals(json.get("errcode").toString())) {
            CacheManager.clearOnly("access_token");
            getAgentInfo();
        }
        return null;
    }

    public static UserInfo getUserInfoByCode(String code) throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=USER_CODE&agentid=AGENTID";
        url = url.replace("ACCESS_TOKEN", getAccessToken()).replace("USER_CODE", code).replace("AGENTID", agentId);
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        System.out.println(responseContent);
        JSONObject json = JSONObject.fromObject(responseContent);
        if ("0".equals(json.get("errcode").toString())) {
            String userId = json.get("UserId").toString();
            return getUserInfo(userId);
        } else if ("40001".equals(json.get("errcode").toString())||"42001".equals(json.get("errcode").toString())) {
            CacheManager.clearOnly("access_token");
            getUserInfoByCode(code);
        }
        return null;
    }


    public static UserInfo getUserInfo(String userId) throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID";
        url = url.replace("ACCESS_TOKEN", getAccessToken()).replace("USERID", userId);
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        System.out.println(responseContent);
        JSONObject json = JSONObject.fromObject(responseContent);
        if ("0".equals(json.get("errcode").toString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            return objectMapper.readValue(responseContent, new TypeReference<UserInfo>() {
            });
        } else if ("40001".equals(json.get("errcode").toString())||"42001".equals(json.get("errcode").toString())) {
            CacheManager.clearOnly("access_token");
            getUserInfo(userId);
        }
        return null;
    }


    public static List<UserInfo> getUserInfoByPartyId(String partyid) throws Exception {
        List<UserInfo> userInfoList = new ArrayList<UserInfo>();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=0";
        url = url.replace("ACCESS_TOKEN", getAccessToken()).replace("DEPARTMENT_ID", partyid);
        ClientRequest request = new ClientRequest(url);
        request.accept("application/json");
        ClientResponse<String> response = request.get(String.class);
        String responseContent = (String) response.getEntity();
        System.out.println(responseContent);
        JSONObject json = JSONObject.fromObject(responseContent);
        if ("0".equals(json.get("errcode").toString())) {
            json = JSONObject.fromObject(responseContent);
            net.sf.json.JSONArray array = json.getJSONArray("userlist");
            if (array != null && array.size() > 0) {
                UserInfo userInfo;
                for (Object str : array) {
                    json = JSONObject.fromObject(str);
                    String userId = (String) json.get("userid");
                    userInfo = getUserInfo(userId);
                    userInfoList.add(userInfo);
                }
            }
        } else if ("40001".equals(json.get("errcode").toString())||"42001".equals(json.get("errcode").toString())) {
            CacheManager.clearOnly("access_token");
            getUserInfoByPartyId(partyid);
        }
        return userInfoList;

    }
}
